﻿using KZ.Express.ENT;
using KZ.Express.Presenter;
using KZ.Express.Resource;
using KZ.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace KZ.Express
{
    public partial class MainView : FormBase
    {
        const string _LIST = "ListView";
        const string _DETAIL = "DetailView";
        List<ToolStripButton> _itemList;
        DataTable _objects;

        public MainView()
        {
            InitializeComponent();
            _itemList = new List<ToolStripButton>(tspToolbar.Items.OfType<ToolStripButton>());
            base.TopLevel = true;
            base._presenter = new PresenterBase(this, new ObjectENT());
        }

        private void MainView_Load(object sender, EventArgs e)
        {
            LoginView view = new LoginView();
            if (view.ShowDialog() == DialogResult.OK)
            {
                SearchCriteria search = new SearchCriteria();
                search.Add("RoleID", UserENT.ROLEID);

                _objects = base._presenter.LoadDataTable<ObjectENT>(search);
                PermissionMenu();
            }
            else
                Application.Exit();
        }

        #region Events

        private void tbcMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangedTab();
        }

        private void tsbInsert_Click(object sender, EventArgs e)
        {
            HandleAction(ActionName.Insert);
        }

        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            HandleAction(ActionName.Update);
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            HandleAction(ActionName.Delete);
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            HandleAction(ActionName.Save);
        }

        private void tsbExit_Click(object sender, EventArgs e)
        {
            HandleAction(ActionName.List);
        }

        private void tsbCloseTab_Click(object sender, EventArgs e)
        {
            CloseTab();
        }

        private void tsmiAccount_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.Partner.AccountListView view = Application.OpenForms["AccountListView"] as KZ.Express.Setup.Partner.AccountListView;
            if (view == null)
                view = new Setup.Partner.AccountListView();
            OpenTab(view);
        }

        private void tsmiCustomer_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.Partner.CustomerListView view = Application.OpenForms["CustomerListView"] as KZ.Express.Setup.Partner.CustomerListView;
            if (view == null)
                view = new Setup.Partner.CustomerListView();
            OpenTab(view);
        }

        private void tsmiCustomerGroup_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.Partner.CustomerGroupView view = Application.OpenForms["CustomerGroupView"] as KZ.Express.Setup.Partner.CustomerGroupView;
            if (view == null)
                view = new Setup.Partner.CustomerGroupView();
            OpenTab(view);
        }

        private void tsmiOriginalPriceList_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.PriceList.OriginalPriceListView view = Application.OpenForms["OriginalPriceListView"] as KZ.Express.Setup.PriceList.OriginalPriceListView;
            if (view == null)
                view = new Setup.PriceList.OriginalPriceListView();
            OpenTab(view);
        }

        private void tsmiCustomerPriceList_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.PriceList.CustomerPriceListView view = Application.OpenForms["CustomerPriceListView"] as KZ.Express.Setup.PriceList.CustomerPriceListView;
            if (view == null)
                view = new Setup.PriceList.CustomerPriceListView();
            OpenTab(view);
        }

        private void tsmiZone_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.PriceList.ZoneListView view = Application.OpenForms["ZoneListView"] as KZ.Express.Setup.PriceList.ZoneListView;
            if (view == null)
                view = new Setup.PriceList.ZoneListView();
            OpenTab(view);
        }

        private void tsmiMenuOrder_Click(object sender, EventArgs e)
        {
            KZ.Express.Order.Order.OrderListView view = Application.OpenForms["OrderListView"] as KZ.Express.Order.Order.OrderListView;
            if (view == null)
                view = new Order.Order.OrderListView();
            OpenTab(view);
        }

        private void tsmiStatistic_Click(object sender, EventArgs e)
        {
            KZ.Express.Order.Order.StatisticView view = Application.OpenForms["StatisticView"] as KZ.Express.Order.Order.StatisticView;
            if (view == null)
                view = new Order.Order.StatisticView();
            OpenTab(view);
        }

        private void tsmiRole_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.KZSystem.RoleListView view = Application.OpenForms["RoleListView"] as KZ.Express.Setup.KZSystem.RoleListView;
            if (view == null)
                view = new Setup.KZSystem.RoleListView();
            OpenTab(view);
        }

        private void tsmiCheckPrice_Click(object sender, EventArgs e)
        {
            CheckPriceView view = Application.OpenForms["CheckPriceView"] as CheckPriceView;
            if (view == null)
            {
                view = new CheckPriceView();
                view.Show();
            }
            else
                view.BringToFront();
        }

        private void tsmiLoginAccount_Click(object sender, EventArgs e)
        {
            KZ.Express.Setup.KZSystem.LoginAccountListView view = Application.OpenForms["LoginAccountView"] as KZ.Express.Setup.KZSystem.LoginAccountListView;
            if (view == null)
                view = new Setup.KZSystem.LoginAccountListView();
            OpenTab(view);
        }

        private void tsmiLogs_Click(object sender, EventArgs e)
        {
            KZ.Express.Order.Log.LogListView view = Application.OpenForms["LogListView"] as KZ.Express.Order.Log.LogListView;
            if (view == null)
                view = new KZ.Express.Order.Log.LogListView();
            OpenTab(view);
        }

        #endregion Events

        #region Shortcut

        private void tsmiInsert_Click(object sender, EventArgs e)
        {
            if (tsbInsert.Enabled) tsbInsert_Click(tsbInsert, null);
        }

        private void tsmiUpdate_Click(object sender, EventArgs e)
        {
            if (tsbUpdate.Enabled) tsbUpdate_Click(tsbUpdate, null);
        }

        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            if (tsbDelete.Enabled) tsbDelete_Click(tsbDelete, null);
        }

        private void tsmiSave_Click(object sender, EventArgs e)
        {
            if (tsbSave.Enabled) tsbSave_Click(tsbSave, null);
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            if (tsbExit.Enabled) tsbExit_Click(tsbExit, null);
        }

        private void tsmiCloseTab_Click(object sender, EventArgs e)
        {
            if (tsbCloseTab.Visible) tsbCloseTab_Click(tsbCloseTab, null);
        }

        private void tsmiCalculation_Click(object sender, EventArgs e)
        {
            if (tbcMain.SelectedTab.Name == "KZ.Express.Order.Order.Order")
            {
                KZ.Express.Order.Order.OrderListView view = Application.OpenForms["OrderListView"] as KZ.Express.Order.Order.OrderListView;
                if (view != null)
                    view.Surcharge();
            }
        }

        private void tsmiImport_Click(object sender, EventArgs e)
        {
            if (tbcMain.SelectedTab.Name == "KZ.Express.Order.Order.Order")
            {
                KZ.Express.Order.Order.OrderListView view = Application.OpenForms["OrderListView"] as KZ.Express.Order.Order.OrderListView;
                if (view != null)
                    view.Import();
            }
            else if (tbcMain.SelectedTab.Name == "KZ.Express.Setup.PriceList.CustomerPrice")
            {
                KZ.Express.Order.Order.OrderListView view = Application.OpenForms["CustomerPriceListView"] as KZ.Express.Order.Order.OrderListView;
                if (view != null)
                    view.Import();
            }
            else if (tbcMain.SelectedTab.Name == "KZ.Express.Setup.PriceList.OriginalPrice")
            {
                KZ.Express.Order.Order.OrderListView view = Application.OpenForms["OriginalPriceListView"] as KZ.Express.Order.Order.OrderListView;
                if (view != null)
                    view.Import();
            }
        }

        private void tsmiExport_Click(object sender, EventArgs e)
        {
            if (tbcMain.SelectedTab.Name == "KZ.Express.Order.Order.Order")
            {
                KZ.Express.Order.Order.OrderListView view = Application.OpenForms["OrderListView"] as KZ.Express.Order.Order.OrderListView;
                if (view != null)
                    view.Export();
            }
        }

        private void exportToCustomerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tbcMain.SelectedTab.Name == "KZ.Express.Order.Order.Order")
            {
                KZ.Express.Order.Order.OrderListView view = Application.OpenForms["OrderListView"] as KZ.Express.Order.Order.OrderListView;
                if (view != null)
                    view.ExportToCustomer();
            }
        }

        #endregion

        #region Private Methods

        private void CloseTab()
        {
            if (tbcMain.TabCount > 0)
            {
                int index = tbcMain.SelectedIndex;

                foreach (Control ctrl in tbcMain.SelectedTab.Controls)
                    ctrl.Dispose();

                tbcMain.SelectedTab.Dispose();
                tsbCloseTab.Enabled = tbcMain.TabCount > 0;

                if (index > 0)
                    tbcMain.SelectedIndex = index - 1;
            }
        }

        /// <summary>
        /// when tab changed, handle toolbar again
        /// if all tab page is removed, disable toolbar
        /// </summary>
        private void ChangedTab()
        {
            if (tbcMain.TabCount > 0)
            {
                string tabName = Global.RemoveNamespace(tbcMain.SelectedTab.Name);
                FormBase frmList = tbcMain.SelectedTab.Controls[tabName + _LIST] as FormBase;
                FormBase frmDetail = tbcMain.SelectedTab.Controls[tabName + _DETAIL] as FormBase;
                FormBase frm = tbcMain.SelectedTab.Controls[tabName] as FormBase;

                if (frmList != null && frmList.Visible)
                    HandleToolbar(frmList.Action, frmList.ObjectID);
                else if (frmDetail != null && frmDetail.Visible)
                    HandleAction(frmDetail.Action);
                else
                    HandleAction(frm.Action);
            }
            else
                HandleToolbar(ActionName.DisableMenu, 0);
        }

        /// <summary>
        /// enable or disable button on toolbar
        /// </summary>
        /// <param name="action"></param>
        private void HandleToolbar(ActionName action, int objectID)
        {
            DataRow[] rows = _objects.Select("ObjectID = " + objectID);
            DataRow row = rows == null || rows.Length == 0 ? null : rows[0];
            _itemList.ForEach(p => p.Enabled = false);
            tsbCloseTab.Enabled = tbcMain.TabCount > 0;
            switch (action)
            {
                case ActionName.List:
                    if (row != null)
                    {
                        string permissionID = "," + Utility.StringParse(row["PermissionID"]) + ",";
                        tsbInsert.Enabled = permissionID.Contains("," + (int)Permissions.Insert + ",");
                        tsbUpdate.Enabled = permissionID.Contains("," + (int)Permissions.Update + ",");
                        tsbDelete.Enabled = permissionID.Contains("," + (int)Permissions.Delete + ",");
                    }
                    else
                    {
                        tsbInsert.Enabled = true;
                        tsbUpdate.Enabled = true;
                        tsbDelete.Enabled = true;
                    }
                    break;

                case ActionName.Insert:
                    if (row != null)
                    {
                        string permissionID = "," + Utility.StringParse(row["PermissionID"]) + ",";
                        tsbSave.Enabled = permissionID.Contains("," + (int)Permissions.Insert + ",");
                    }
                    else
                        tsbSave.Enabled = true;
                    tsbExit.Enabled = true;
                    break;
                case ActionName.Update:
                    if (row != null)
                    {
                        string permissionID = "," + Utility.StringParse(row["PermissionID"]) + ",";
                        tsbSave.Enabled = permissionID.Contains("," + (int)Permissions.Update + ",");
                    }
                    else
                        tsbSave.Enabled = true;
                    tsbExit.Enabled = true;
                    break;

                case ActionName.ListWithDeleteSave:
                    if (row != null)
                    {
                        string permissionID = "," + Utility.StringParse(row["PermissionID"]) + ",";
                        tsbDelete.Enabled = permissionID.Contains("," + (int)Permissions.Delete + ",");
                        tsbSave.Enabled = permissionID.Contains("," + (int)Permissions.InsertAndUpdate + ",");
                    }
                    else
                    {
                        tsbDelete.Enabled = true;
                        tsbSave.Enabled = true;
                    }
                    break;
                case ActionName.View:
                    tsbExit.Enabled = true;
                    break;
            }
        }

        private void PermissionMenu()
        {
            foreach (DataRow row in _objects.Rows)
            {
                string permissionID = "," + Utility.StringParse(row["PermissionID"]) + ",";
                if (permissionID.Contains("," + (int)Permissions.Select + ","))
                {
                    string objectCode = Utility.StringParse(row["ObjectCode"]);
                    ToolStripItem[] items = menuStrip1.Items.Find(objectCode, true);
                    items[0].Enabled = true;
                }
            }

            foreach (ToolStripMenuItem item in menuStrip1.Items)
            {
                if (item.HasDropDownItems)
                    DisableParentMenu(item);
            }
        }

        private void DisableParentMenu(ToolStripMenuItem parent)
        {
            bool isEnable = false;
            IEnumerable<ToolStripMenuItem> items = parent.DropDownItems.OfType<ToolStripMenuItem>();
            foreach (ToolStripMenuItem item in items)
            {
                if (item.HasDropDownItems)
                    DisableParentMenu(item);

                if (item.Enabled)
                {
                    isEnable = true;
                    break;
                }
            }

            parent.Enabled = isEnable;
        }

        #endregion Private Methods

        #region Public Methods

        public void OpenTab(FormBase frm)
        {
            frm.Dock = DockStyle.Fill;
            Type type = frm.GetType();
            string typeName = type.FullName.Replace(_LIST, String.Empty).Replace(_DETAIL, String.Empty);

            int index;
            if ((index = tbcMain.TabPages.IndexOfKey(typeName)) == -1)
            {
                tbcMain.TabPages.Add(typeName, frm.Text);
                index = tbcMain.TabCount - 1;

                tbcMain.TabPages[index].Controls.Add(frm);
            }
            else
            {
                if (!tbcMain.TabPages[index].Controls.ContainsKey(frm.Name))
                    tbcMain.TabPages[index].Controls.Add(frm);
                else
                    frm = tbcMain.TabPages[index].Controls[frm.Name] as FormBase;
            }

            string frmName = Global.RemoveNamespace(typeName);
            FormBase frmList = Application.OpenForms[frmName + _LIST] as FormBase;
            FormBase frmDetail = Application.OpenForms[frmName + _DETAIL] as FormBase;
            if (frm.Name.EndsWith(_LIST))
            {
                //if (frmList != null && frmList.Visible)
                if (frmDetail != null)
                {
                    frmDetail.Dispose();
                    frmDetail.Close();
                }
            }
            else if (frm.Name.EndsWith(_DETAIL))
            {
                if (frmList != null)
                    frmList.Hide();
            }

            frm.Show();
            tbcMain.SelectedIndex = index;
            if (tbcMain.TabCount > 0) { HandleToolbar(frm.Action, frm.ObjectID); }
        }

        public void HandleAction(ActionName action)
        {
            FormBase frm;
            string tabName = tbcMain.SelectedTab.Name;
            switch (action)
            {
                case ActionName.Save:
                    tabName = Global.RemoveNamespace(tabName);
                    if (tabName == "ZoneView" || tabName == "CustomerGroupView" || tabName == "LoginAccountView")
                        frm = Application.OpenForms[tabName] as FormBase;
                    else
                        frm = Application.OpenForms[tabName + _DETAIL] as FormBase;
                    frm.Save();
                    break;

                case ActionName.Delete:
                    tabName = Global.RemoveNamespace(tabName);
                    if (tabName == "CustomerGroupView" || tabName == "LoginAccountView")
                        frm = Application.OpenForms[tabName] as FormBase;
                    else
                        frm = Application.OpenForms[tabName + _LIST] as FormBase;
                    frm.Delete();
                    break;

                case ActionName.Insert:
                    frm = Global.CreateInstance(tabName + _DETAIL);
                    if (frm != null)
                    {
                        frm.Action = action;
                        OpenTab(frm);
                    }
                    break;

                case ActionName.Update:
                    frm = Global.CreateInstance(tabName + _DETAIL);
                    if (frm != null)
                    {
                        tabName = Global.RemoveNamespace(tabName);
                        FormBase frmList = Application.OpenForms[tabName + _LIST] as FormBase;

                        frm.Action = action;
                        frm.EntityID = frmList.GetSelected();
                        if (frm.EntityID == 0) return;
                        OpenTab(frm);
                    }
                    break;

                case ActionName.List:
                    tabName = Global.RemoveNamespace(tabName);
                    frm = Application.OpenForms[tabName + _LIST] as FormBase;
                    OpenTab(frm);
                    break;

                case ActionName.View:
                    frm = Global.CreateInstance(tabName + _DETAIL);
                    if (frm != null)
                    {
                        tabName = Global.RemoveNamespace(tabName);
                        FormBase frmList = Application.OpenForms[tabName + _LIST] as FormBase;

                        frm.EntityID = frmList.GetSelected();
                        if (frm.EntityID == 0) return;
                        OpenTab(frm);
                    }
                    break;
            }
        }

        #endregion
    }
}